import axios from "axios";
import { Message, Loading } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import Vue from "vue";
// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 50000 // request timeout
});

// request interceptor
service.interceptors.request.use(
    config => {
        // 加载条
        const { isLoading } = store.getters;
        if (isLoading) {
            showLoading(config);
        }
        // do something before request is sent
        // if (token) {
        //     config.headers['token'] = getToken()
        // }
        return config;
    },
    error => {
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

let loadingInstance,
    loadingRequestCount = 0;
const showLoading = () => {
    // element的服务方式 target 我这边取的是表格 项目是后台系统 每个页面都有表格 类似整个表格loading
    //和在表格配置v-loading一样的效果，这么做是全局实现了，不用每个页面单独去v-loading
    if (loadingRequestCount == 0) {
        // console.error(document.querySelector('.el-table'), 'el-table')
        loadingInstance = Loading.service({
            fullscreen: false,
            lock: true,
            target: document.querySelector(".el-table"),
            text: "加载中"
        });
    }
    loadingRequestCount++;
};

const hideLoading = () => {
    //关闭加载条
    if (loadingRequestCount <= 0) return;
    loadingRequestCount--;
    if (loadingRequestCount == 0) {
        Vue.nextTick(() => {
            // 以服务的方式调用的 Loading 需要异步关闭
            loadingInstance.close();
        });
    }
};

// response interceptor
service.interceptors.response.use(
    response => {
        if (store.getters.isLoading) {
            //关闭加载条
            hideLoading();
        }
        if (response.data.success) {
            return response;
        } else {
            Message({
                message: response.data.msg,
                type: "error",
                duration: 2000
            });
            return response;
        }
    },
    error => {
        console.log("err" + error); // for debug
        Message({
            message: error.message,
            type: "error",
            duration: 5 * 1000
        });
        return Promise.reject(error);
    }
);

export default service;